package com.cn.demo2.test1;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class ConstructorUse {
    public ConstructorUse(String message){
        System.out.println("Constructor called with message: " + message);
    }

    private ConstructorUse(int value){
        System.out.println("Private Constructor called with value: " + value);
    }

    public void print(){
        System.out.println("hello!Boy!");
    }

    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        //获取Class对象
        Class<ConstructorUse> clazz = ConstructorUse.class;
        //使用公共构造方法创建对象
        //获取构造方法
        Constructor<ConstructorUse> constructor = clazz.getConstructor(String.class);
        //创建对象
        //T newInstance(Object... initargs)
        //`initargs`：构造方法需要的参数列表，按顺序传递。
        ConstructorUse constructorUse = constructor.newInstance("Hello,Reflection!");
        constructorUse.print();

        //使用私有构造方法创建对象
        Constructor<ConstructorUse> declaredConstructor = clazz.getDeclaredConstructor(int.class);

        //取消访问限制
        declaredConstructor.setAccessible(true);

        //创建对象
        ConstructorUse constructorUse1 = declaredConstructor.newInstance(42);
        constructorUse1.print();


    }
}
